package cn.acewill.yxd.yunxundian.ui.user;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.EmailAdpater;
import cn.acewill.yxd.yunxundian.model.EmailBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;


/**
 * Created by XXX on 2017/4/3.
 */
public class EmailInfoActivity extends BaseActivity implements AdapterView.OnItemClickListener{

    private ListView myList;
    private  EmailAdpater adpater;
    private ArrayList<EmailBean> emaillist;
    private RelativeLayout loadingview;
    private TextView noNetWork;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.emailinfo_list);
        initView();
    }

    public void initView(){
        Toolbar myToolBar = (Toolbar) findViewById(R.id.myToolBar);
        myToolBar.setTitle("");
        myToolBar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(myToolBar);
        myToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        this.noNetWork = (TextView) findViewById(R.id.noNetWork);
        noNetWork.setOnClickListener(new View.OnClickListener() { //去设置页面
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        this.loadingview= (RelativeLayout) findViewById(R.id.loadingRel);
        ImageView addEmail = (ImageView) findViewById(R.id.addEmail);
        this.myList= (ListView) findViewById(R.id.myList);
        this.myList.setOnItemClickListener(this);
        addEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(EmailInfoActivity.this,AddEmailActivity.class));
            }
        });
        setShowOrGone(1);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EmailBean bean = (EmailBean) parent.getItemAtPosition(position);
        Intent in=new Intent(this,EmailDetailActivity.class);
        in.putExtra("EmailName",bean.getMailName());
        in.putExtra("EmailAddress",bean.getMailAddress());
        in.putExtra("mailid",bean.getId());
        startActivityForResult(in,1001);
    }

    //获取邮箱信息的list
    public void getEmialList(){
        Map<String,String> map = new HashMap<>();
        map.put("task","loadeMailListByEmpid");
        map.put("empid", MainActivity.id+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    setShowOrGone(2);
                    String res[] = result.split("\\|");
                    if (res[0].equals("200")){ //bug 数据为空的返回结果也是200，导致数据转化失败
                        if (res[3].contains("[")&&res[3].contains("]")){
                            Gson gson = new Gson();
                            Type typeList = new TypeToken<ArrayList<EmailBean>>() {
                            }.getType();
                            emaillist = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
                            adpater = new EmailAdpater(EmailInfoActivity.this,emaillist);
                            myList.setAdapter(adpater);
                            adpater.notifyDataSetChanged();
                        }else{
                            //请求成功但没数据
                            BaseActivity.showAnimaDialog(EmailInfoActivity.this,"当前无邮箱信息，可点击下角按钮添加");
                            setShowOrGone(2);
                        }

                    }
                }
                @Override
                public void onFailture() {
                    BaseActivity.showAnimaDialog(EmailInfoActivity.this,"数据请求失败，请检查网络状态");
                    setShowOrGone(3);
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接收网络状态的判断广播
    NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo!=null){
                whetherConnectNetWork=1;

                getEmialList();
            }else{
               setShowOrGone(3);
            }
        }
    }

    public void setShowOrGone(int k){
        if (k==1){
            loadingview.setVisibility(View.VISIBLE);
            noNetWork.setVisibility(View.GONE);
            myList.setVisibility(View.GONE);
        }
        if (k==2){
            loadingview.setVisibility(View.GONE);
            noNetWork.setVisibility(View.GONE);
            myList.setVisibility(View.VISIBLE);
        }
        if (k==3){
            loadingview.setVisibility(View.GONE);
            noNetWork.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
    }
}
